<route lang="json5">
{
  style: { navigationBarTitleText: 'Scooter Rental' },
}
</route>

<template>
  <view class="rent-container">
    <view class="info-section">
      <view class="info-item">
        <text class="label">Scooter ID</text>
        <text class="value">#{{ scooterId }}</text>
      </view>

      <view class="info-item">
        <text class="label">Start Time</text>
        <view class="time-picker-wrapper">
          <text class="selected-time">{{ startTimeText }}</text>
          <text class="arrow">▼</text>
        </view>
        <uni-datetime-picker
          ref="timePicker"
          type="datetime"
          :value="startTime"
          :start="currentTime"
          return-type="timestamp"
          @change="onTimeSelect"
          :popup-style="{ backgroundColor: '#fff' }"
        />
      </view>

      <view class="info-item">
        <text class="label">Rental Duration</text>
        <view class="duration-select">
          <text
            v-for="duration in durations"
            :key="duration.hour"
            :class="['duration-option', { active: selectedDuration === duration.hour }]"
            @click="selectedDuration = duration.hour"
          >
            {{ formatDuration(duration.hour) }}
          </text>
        </view>
      </view>
      <view class="info-item">
        <text class="label">Estimated Cost</text>
        <text class="value price">${{ calculatePrice }}</text>
      </view>
    </view>

    <view class="action-section">
      <button class="confirm-btn" @click="handleRent">Confirm Rental</button>
    </view>
  </view>
  <bank-card-payment
    ref="paymentPopup"
    :amount="calculatePrice"
    :saved-card="savedCard"
    @success="onPaymentSuccess"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getPrice } from '@/service/pricing'
import { userInfo } from '@/service/user'
import { rent } from '@/service/rent' // 添加 rent 服务
import { formatDuration } from '@/utils/timeFormat'
import BankCardPayment from '@/components/bank-card-payment/index.vue'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const scooterId = ref('')

// 价格方案
const durations = ref([])
const selectedDuration = ref(0)

// 获取价格方案
const getPricingPlans = async () => {
  try {
    const { data } = await getPrice()
    durations.value = data.records.map((item) => ({
      hour: item.hour,
      price: item.price,
    }))
    if (durations.value.length > 0) {
      selectedDuration.value = durations.value[0].hour
    }
  } catch (error) {
    uni.showToast({
      title: '获取价格方案失败',
      icon: 'none',
    })
  }
}

// 计算预估费用
const calculatePrice = computed(() => {
  const selectedPlan = durations.value.find((d) => d.hour === selectedDuration.value)
  return selectedPlan ? selectedPlan.price : 0
})

onMounted(() => {
  getPricingPlans()
})

// 开始时间，改为使用实际选择的时间
const startTime = ref(new Date().getTime())
const currentTime = new Date().toISOString()

const startTimeText = computed(() => {
  const date = new Date(startTime.value)
  return date.toLocaleString('en-US', {
    weekday: 'short', // 添加星期显示
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true, // 使用12小时制
  })
})

const timePicker = ref()

const onTimeSelect = (value: number) => {
  if (value) {
    startTime.value = value
    console.log('Selected time:', new Date(startTime.value).toLocaleString())
  }
}

const paymentPopup = ref(null)
const savedCard = ref(null)

// 添加位置信息的响应式数据
const location = ref({
  longitude: 0,
  latitude: 0,
})

// 处理租赁确认
const handleRent = async () => {
  try {
    // 获取用户信息
    const { data } = await userInfo(userStore.userInfo.account)
    savedCard.value = data.bankCardId
      ? {
          bankCardId: data.bankCardId,
          bankCardExpiryMonth: data.bankCardExpiryMonth, // 根据实际返回字段修改
          bankCardExpiryYear: data.bankCardExpiryYear, // 根据实际返回字段修改
          bankCardCvv: data.bankCardCvv, // 添加 CVV
        }
      : null

    uni.showModal({
      title: 'Confirm Rental',
      content: `Do you want to rent scooter #${scooterId.value} for ${formatDuration(selectedDuration.value)} starting from ${startTimeText.value}?`,
      success: (res) => {
        if (res.confirm) {
          paymentPopup.value.show()
        }
      },
    })
  } catch (error) {
    uni.showToast({
      title: 'Failed to get user info',
      icon: 'none',
    })
  }
}

// 处理支付成功
const onPaymentSuccess = async () => {
  try {
    uni.showLoading({ title: 'Processing rental...' })

    // 发送租赁请求，包含位置信息
    await rent(
      scooterId.value,
      startTime.value,
      selectedDuration.value,
      calculatePrice.value,
      location.value.longitude,
      location.value.latitude,
    )

    uni.showToast({
      title: 'Rental Success',
      icon: 'success',
    })

    // 延迟后跳转到首页
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index',
      })
    }, 1500)
  } catch (error) {
    uni.showToast({
      title: 'Rental failed',
      icon: 'none',
    })
  } finally {
    uni.hideLoading()
  }
}

onMounted(async () => {
  getPricingPlans()
})

onLoad((options) => {
  if (options.scooterId) {
    scooterId.value = options.scooterId
  }
  if (options.longitude && options.latitude) {
    location.value.longitude = options.longitude
    location.value.latitude = options.latitude
  }
  console.log('options', options)
})
</script>

<style lang="scss">
.rent-container {
  padding: 20px;
}

.info-section {
  padding: 16px;
  background: #fff;
  border-radius: 8px;

  .info-item {
    margin-bottom: 20px;

    .label {
      display: block;
      margin-bottom: 8px;
      color: #666;
    }

    .value {
      font-size: 16px;
      color: #333;

      &.price {
        font-size: 24px;
        font-weight: bold;
        color: #f60;
      }
    }
  }
}

.duration-select {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;

  .duration-option {
    padding: 8px 16px;
    color: #666;
    border: 1px solid #ddd;
    border-radius: 4px;

    &.active {
      color: #fff;
      background: #007aff;
      border-color: #007aff;
    }
  }
}

.action-section {
  margin-top: 30px;

  .confirm-btn {
    width: 100%;
    padding: 12px;
    font-size: 16px;
    color: #fff;
    background: #007aff;
    border: none;
    border-radius: 6px;
  }
}

.time-picker-wrapper {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  pointer-events: none;

  .selected-time {
    font-size: 16px;
    color: #333;
  }

  .arrow {
    font-size: 12px;
    color: #666;
  }

  &:active {
    background: #f5f5f5;
  }
}

.time-picker {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 4px;

  .icon {
    font-size: 12px;
    color: #666;
  }
}
</style>
